package com.hzeport.bgs22emduty.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.nacos.client.naming.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hzeport.bgs22emduty.config.login.LoginCompoentService;
import com.hzeport.bgs22emduty.config.login.UserInfoDetailVO;
import com.hzeport.bgs22emduty.dto.emergencyCall.ScreenDutyEmergencyCallDTO;
import com.hzeport.bgs22emduty.dto.emergencyCall.ScreenDutyEmergencyCallDetailDTO;
import com.hzeport.bgs22emduty.dto.emergencyCall.ScreenDutyEmergencyCallRemoveDTO;
import com.hzeport.bgs22emduty.dto.emergencyCall.ScreenDutyEmergencyCallSaveDTO;
import com.hzeport.bgs22emduty.dto.experience.ScreenDutyExperienceDetailDTO;
import com.hzeport.bgs22emduty.entity.*;
import com.hzeport.bgs22emduty.enums.DeleteFlagEnum;
import com.hzeport.bgs22emduty.outbound.AppendixRepository;
import com.hzeport.bgs22emduty.outbound.BasePersonInfoRepository;
import com.hzeport.bgs22emduty.outbound.ParamDictionaryRepository;
import com.hzeport.bgs22emduty.outbound.db.ScreenDutyEmergencyCallRepositoryImpl;
import com.hzeport.bgs22emduty.service.ScreenDutyEmergencyCallService;
import com.hzeport.bgs22emduty.vo.file.FileVO;
import com.hzeport.bgs22emduty.common.base.BaseServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * ${comments}
 *
 * @author code generator
 * @date 2023-02-14 09:39:44
 */
@Service
@Slf4j
public class ScreenDutyEmergencyCallServiceImpl extends BaseServiceImpl<ScreenDutyEmergencyCallRepositoryImpl, ScreenDutyEmergencyCall> implements ScreenDutyEmergencyCallService {

    @Resource
    private LoginCompoentService loginCompoentService;
    @Resource
    private AppendixRepository appendixRepository;
    @Resource
    private BasePersonInfoRepository basePersonInfoRepository;
    @Resource
    private ParamDictionaryRepository paramDictionaryRepository;

    @Override
    public Page<ScreenDutyEmergencyCall> getScreenDutyEmergencyCallPage(ScreenDutyEmergencyCallDTO dto) {
        UserInfoDetailVO userInfoDetailVO = loginCompoentService.getUserInfo();
        LambdaQueryWrapper<ScreenDutyEmergencyCall> queryWrapper = new LambdaQueryWrapper<>();
//        if (!userInfoDetailVO.getRole().contains("ZGGLY")) {
            queryWrapper.eq(StringUtils.isNotBlank(userInfoDetailVO.getCustomscode()), ScreenDutyEmergencyCall::getCustomId, userInfoDetailVO.getCustomscode());
//        }
        if (!org.springframework.util.CollectionUtils.isEmpty(dto.getTimes())&&dto.getTimes().get(0)!=null){
            LocalDate localDate=LocalDate.parse(dto.getTimes().get(0));
            queryWrapper.ge(ScreenDutyEmergencyCall::getCreateTime,localDate.atStartOfDay());
        }
        if (!org.springframework.util.CollectionUtils.isEmpty(dto.getTimes())&&dto.getTimes().get(1)!=null){
            LocalDate localDate=LocalDate.parse(dto.getTimes().get(1));
            queryWrapper.le(ScreenDutyEmergencyCall::getCreateTime,localDate.atTime(23,59,59));
        }
        if (!StringUtils.isEmpty(dto.getKeyWord())){
            queryWrapper.like(ScreenDutyEmergencyCall::getTitle,dto.getKeyWord());
        }
        if (!StringUtils.isEmpty(dto.getCustomId())){
            queryWrapper.like(ScreenDutyEmergencyCall::getCustomId,dto.getCustomId());
        }


        queryWrapper.orderByDesc(ScreenDutyEmergencyCall::getCreateTime);
        Page<ScreenDutyEmergencyCall> page = repository.page(new Page<>(dto.getPageNum(), dto.getPageSize()), queryWrapper);
        page.getRecords().forEach(screenDutyWork->{
            if (screenDutyWork.getCreateBy()!=null) {
                BasePersonInfo personInfo = basePersonInfoRepository.getOne(new LambdaQueryWrapper<BasePersonInfo>()
                        .eq(BasePersonInfo::getUserno, screenDutyWork.getCreateBy()),false);
                if (personInfo!=null){
                    screenDutyWork.setCreateBy(personInfo.getUsername());
                    screenDutyWork.setCreatePerson(personInfo.getUsername());
                }
                ParamDictionary one = paramDictionaryRepository.getOne(new LambdaQueryWrapper<ParamDictionary>()
                        .eq(ParamDictionary::getParamCode, screenDutyWork.getTitle())
                        .eq(ParamDictionary::getParamModule,"LLLX"),false);
                if (one!=null){
                    screenDutyWork.setTitleName(one.getParamName());
                }
            }
        });
        return page;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Object saveEmergencyCalls(ScreenDutyEmergencyCallSaveDTO dto) throws Exception {
        UserInfoDetailVO userInfoDetailVO = loginCompoentService.getUserInfo();
        if (StringUtils.isEmpty(dto.getPhone())){
            throw new Exception("手机号不能为空");
        }
        ScreenDutyEmergencyCall screenDutyEmergencyCall = new ScreenDutyEmergencyCall();
        BeanUtil.copyProperties(dto,screenDutyEmergencyCall);
        if (StringUtils.isEmpty(screenDutyEmergencyCall.getId())) {
            screenDutyEmergencyCall.setCustomId(userInfoDetailVO.getCustomscode());
            screenDutyEmergencyCall.setCustomName(userInfoDetailVO.getCustomsName());
            screenDutyEmergencyCall.setCreateBy(userInfoDetailVO.getUserId());
            screenDutyEmergencyCall.setCreateTime(LocalDateTime.now());
            screenDutyEmergencyCall.setUpdateBy(userInfoDetailVO.getUserId());
            screenDutyEmergencyCall.setUpdateTime(LocalDateTime.now());
            screenDutyEmergencyCall.setDelFlag(DeleteFlagEnum.NOT_DELETE.getValue());
            repository.save(screenDutyEmergencyCall);
        }else {
            ScreenDutyEmergencyCall byId = repository.getById(screenDutyEmergencyCall.getId());
            if (byId != null){
                screenDutyEmergencyCall.setRecVersion(byId.getRecVersion());
            }
            screenDutyEmergencyCall.setUpdateBy(userInfoDetailVO.getUserId());
            screenDutyEmergencyCall.setUpdateTime(LocalDateTime.now());
            repository.updateById(screenDutyEmergencyCall);
            appendixRepository.remove(new LambdaUpdateWrapper<Appendix>().eq(Appendix::getRelevanceId, screenDutyEmergencyCall.getId()));
        }
        List<FileVO> files = dto.getFiles();
        if (!CollectionUtils.isEmpty(files)) {
            files.forEach(fileVO -> {
                Appendix byId = appendixRepository.getById(fileVO.getId());
                LambdaUpdateWrapper<Appendix> wrapper = new LambdaUpdateWrapper<>();
                wrapper.eq(Appendix::getId, fileVO.getId())
                        .eq(byId != null&&byId.getRecVersion()!=null,Appendix::getRecVersion,byId.getRecVersion()).set(Appendix::getRelevanceId, screenDutyEmergencyCall.getId());
                appendixRepository.update(wrapper);
            });
        }
        return "1";
    }

    @Override
    public Object remove(ScreenDutyEmergencyCallRemoveDTO screenDutyEmergencyCallRemoveDTO) {
        return repository.removeById(screenDutyEmergencyCallRemoveDTO.getId());
    }

    @Override
    public Object detail(String id) {
        ScreenDutyEmergencyCall screenDutyWork=repository.getById(id);
        if (screenDutyWork.getCreateBy()!=null) {
            BasePersonInfo personInfo = basePersonInfoRepository.getOne(new LambdaQueryWrapper<BasePersonInfo>()
                    .eq(BasePersonInfo::getUserno, screenDutyWork.getCreateBy()),false);
            if (personInfo!=null){
                screenDutyWork.setCreateBy(personInfo.getUsername());
                screenDutyWork.setCreatePerson(personInfo.getUsername());
            }
        }
        ScreenDutyEmergencyCallDetailDTO screenDutyWorkDetailDTO=new ScreenDutyEmergencyCallDetailDTO();
        BeanUtils.copyProperties(screenDutyWork,screenDutyWorkDetailDTO);
        ParamDictionary one = paramDictionaryRepository.getOne(new LambdaQueryWrapper<ParamDictionary>()
                .eq(ParamDictionary::getParamCode, screenDutyWork.getTitle())
                .eq(ParamDictionary::getParamModule,"LLLX"),false);
        if (one!=null){
            screenDutyWorkDetailDTO.setTitleName(one.getParamName());
        }
        List<FileVO> fileVOS = appendixRepository.list(new LambdaQueryWrapper<Appendix>().eq(Appendix::getRelevanceId, id))
                .stream().map(appendix -> {
                    FileVO fileVO = new FileVO();
                    BeanUtils.copyProperties(appendix,fileVO);
                    return fileVO;
                }).collect(Collectors.toList());
        screenDutyWorkDetailDTO.setFiles(fileVOS);
        return screenDutyWorkDetailDTO;
    }
}
